package com.xiaoyun.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaoyun.enums.CommentLevel;
import com.xiaoyun.enums.YesOrNo;
import com.xiaoyun.mapper.ItemsCommentsMapper;
import com.xiaoyun.mapper.ItemsMapper;
import com.xiaoyun.mapper.ItemsMapperCustom;
import com.xiaoyun.pojo.*;
import com.xiaoyun.repository.ItemsImgRepository;
import com.xiaoyun.repository.ItemsParamRepository;
import com.xiaoyun.repository.ItemsSpecRepository;
import com.xiaoyun.service.ItemService;
import com.xiaoyun.utils.DesensitizationUtil;
import com.xiaoyun.utils.PagedGridResult;
import com.xiaoyun.vo.CommentLevelCountsVO;
import com.xiaoyun.vo.ItemCommentVO;
import com.xiaoyun.vo.SearchItemsVO;
import com.xiaoyun.vo.ShopcartVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class ItemServiceImpl implements ItemService {

    private final ItemsMapper itemsMapper;

    private final ItemsImgRepository itemsImgRepository;

    private final ItemsSpecRepository itemsSpecRepository;

    private final ItemsParamRepository itemsParamRepository;

    private final ItemsCommentsMapper itemsCommentsMapper;

    private final ItemsMapperCustom itemsMapperCustom;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Items queryItemById(String itemId) {
        return itemsMapper.selectByPrimaryKey(itemId);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<ItemsImg> queryItemImgList(String itemId) {
        return itemsImgRepository.findByItemId(itemId);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<ItemsSpec> queryItemSpecList(String itemId) {
        return itemsSpecRepository.findByItemId(itemId);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public ItemsParam queryItemParam(String itemId) {
        return itemsParamRepository.findByItemId(itemId);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public CommentLevelCountsVO queryCommentCounts(String itemId) {
        Integer goodCount = getCommonCounts(itemId, CommentLevel.GOOD.type);
        Integer normalCount = getCommonCounts(itemId, CommentLevel.NORMAL.type);
        Integer badCount = getCommonCounts(itemId, CommentLevel.BAD.type);
        Integer totalCount = goodCount + normalCount + badCount;

        CommentLevelCountsVO commentLevelCountsVO = new CommentLevelCountsVO();
        commentLevelCountsVO.setBadCounts(badCount);
        commentLevelCountsVO.setNormalCounts(normalCount);
        commentLevelCountsVO.setGoodCounts(goodCount);
        commentLevelCountsVO.setTotalCounts(totalCount);

        return commentLevelCountsVO;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public PagedGridResult queryPagedComments(String itemId, Integer level, Integer page, Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
        map.put("itemId", itemId);
        map.put("level", level);
        PageHelper.startPage(page, pageSize);
        List<ItemCommentVO> list = itemsMapperCustom.queryItemComments(map);
        //脱敏
        list.forEach(item -> {
            item.setNickname(DesensitizationUtil.commonDisplay(item.getNickname()));
        });
        return setterPagedGrid(list, page);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public PagedGridResult searchItems(String keywords, String sort, Integer page, Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
        map.put("keywords", keywords);
        map.put("sort", sort);
        PageHelper.startPage(page, pageSize);
        List<SearchItemsVO> list = itemsMapperCustom.searchItems(map);

        return setterPagedGrid(list, page);
    }

    @Override
    public PagedGridResult searchItems(Integer catId, String sort, Integer page, Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
        map.put("catId", catId);
        map.put("sort", sort);
        PageHelper.startPage(page, pageSize);
        List<SearchItemsVO> list = itemsMapperCustom.searchItemsByThirdCat(map);
        return setterPagedGrid(list, page);
    }

    @Override
    public List<ShopcartVO> queryItemsBySpecIds(String specIds) {
        List<String> specIdList = Arrays.asList(specIds.split(","));
        return itemsMapperCustom.queryItemsBySpecIds(specIdList);
    }

    @Override
    public ItemsSpec queryItemSpecById(String specId) {
        return itemsSpecRepository.findById(specId).get();
    }

    @Override
    public String queryItemMainImgById(String itemId) {
        ItemsImg result = itemsImgRepository.findByItemIdAndIsMain(itemId, YesOrNo.YES.type);
        return result != null ? result.getUrl() : "";
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void decreaseItemSpecStock(String itemSpecId, int buyCounts) {
        //TODO 分布式锁
        int result = itemsMapperCustom.decreaseItemSpecStock(itemSpecId, buyCounts);
        if (result != 1) {
            throw new RuntimeException("订单创建失败,库存不足");
        }

    }

    private PagedGridResult setterPagedGrid(List<?> list, Integer page) {
        PageInfo<?> pageList = new PageInfo<>(list);
        PagedGridResult grid = new PagedGridResult();
        grid.setPage(page);
        grid.setRows(list);
        grid.setTotal(pageList.getPages());
        grid.setRecords(pageList.getTotal());
        return grid;
    }


    @Transactional(propagation = Propagation.SUPPORTS)
    Integer getCommonCounts(String itemId, Integer level) {
        ItemsComments itemsComments = new ItemsComments();
        itemsComments.setItemId(itemId);
        if (level != null) {
            itemsComments.setCommentLevel(level);
        }
        return itemsCommentsMapper.selectCount(itemsComments);
    }
}
